package server;

import common.RPCRequest;
import common.RPCResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class WorkThread implements Runnable{
    private Socket socket;
    private ServiceProvider serviceProvider;
    public WorkThread(Socket socket, ServiceProvider serviceProvider){
        this.socket = socket;
        this.serviceProvider = serviceProvider;
    }
    @Override
    public void run() {
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            RPCRequest request = (RPCRequest) inputStream.readObject();
            System.out.println(request);
            RPCResponse response = getResponse(request);
            outputStream.writeObject(response);
            outputStream.flush();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private RPCResponse getResponse(RPCRequest request){
        try {
            Object service = serviceProvider.getService(request.getInterfaceName());
            Method method = service.getClass().getMethod(request.getMethodName(), request.getParamsTypes());
            Object data = method.invoke(service, request.getParams());
            return RPCResponse.success(data);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            return RPCResponse.error();
        }
    }
}
